﻿@{
    Layout = null;
    DeliveryManage.Models.ReturnMsgModel returnMsg = ViewBag.ReturnMsgModel;
}
@model DeliveryManage.Model.Pro_Orders
<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>创建订单</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,initial-scale=1.0,user-scalable=no" />
    <link rel="stylesheet" href="~/Content/font.css">
    <link rel="stylesheet" href="~/Content/framemain.css">
    <link rel="stylesheet" href="~/Content/pagination.css" />
    <script type="text/javascript" src="~/Content/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="~/Scripts/common.js"></script>
    <script type="text/javascript" src="~/Scripts/framemain.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <style>
        .layui-table img {
            max-width: inherit;
        }

        .pro-img {
            border-radius: 5px;
            border: 1px solid #f2f2f2;
        }

        .layui-layer-molv .layui-layer-btn .layui-layer-btn1 {
            background: #fff !important;
            border: 1px solid #dedede;
        }

        .txt-number {
            width: 50px;
            float: left;
        }

        .btn-number {
            width: 40px;
            float: left;
        }

        .txt-col {
            color: red !important;
        }
    </style>
    <script type="text/javascript">
     $(function () {
         //操作提示
         if(@returnMsg.code== 400){
             layer.alert('@returnMsg.msg', { icon: 5, title: '提示' }, function (index) {
             })
         }
         $(document).ready(function () {
             $("#myfrom").submit(function () {
                 var data = $(this).serialize();
                 layer.confirm('确认提交吗?', { icon: 3, title: '提示' }, function (index) {
                     $.ajax({
                         type: "POST",
                         url: "/Order/SaveOrder",
                         data: data,
                         success: function (obj) {
                             if (obj.status == true) {
                                 layer.msg(obj.msg, { icon: 6, title: '提示' }, function (index) {
                                     window.location.href = '/Order/OrderList';
                                 });
                             } else {
                                 layer.confirm(obj.msg, { icon: 5, title: '提示' }, function (index) {
                                     layer.close();
                                     location.reload();
                                 });
                             }
                         }
                     })
                     layer.close();
                 });
                 return false;

             })
         })
     });
    </script>
</head>
<body>
    <form id="myfrom" class="tab-content layui-form" action="" lay-filter="example">
        @{
            @Html.HiddenFor(m => m.Id)
            @Html.Hidden("AddOrEdit", (string)ViewBag.AddOrEdit)
            @Html.Hidden("OrderGoods", "")
            <div class="x-nav">
                <span class="layui-breadcrumb">
                    <a href="javascript:;">首页</a>
                    <a><cite>创建订单</cite></a>
                </span>
            </div>
            if (returnMsg.code == 200)
            {
                <div class="layui-fluid">
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md12">
                            <div class="layui-card">
                                <div class="layui-card-body ">
                                    <blockquote class="layui-elem-quote">客户基础信息</blockquote>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">客户姓名</label>
                                        <div class="layui-input-block">
                                            @Html.TextBoxFor(m => m.CustomerName, new { @datatype = "s2-30", @autocomplete = "off", @class = "layui-input", @sucmsg = " ", id = "CustomerName", placeholder = "请输入客户姓名" })
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">客户电话</label>
                                        <div class="layui-input-block">
                                            @Html.TextBoxFor(m => m.CustomerTel, new { @datatype = "s1-11", @autocomplete = "off", @class = "layui-input", @sucmsg = " ", id = "CustomerTel", placeholder = "请输入客户电话" })
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">客户性别</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="CustomerSex" value="true" title="男" checked>
                                            <input type="radio" name="CustomerSex" value="false" title="女">
                                        </div>
                                    </div>

                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">客户地址</label>
                                        <div class="layui-input-block">
                                            @Html.TextAreaFor(m => m.CustomerAddress, new { @datatype = "s1-128", @autocomplete = "off", @class = "layui-textarea", @sucmsg = " ", id = "CustomerAddress", placeholder = "请输入客户收货地址" })
                                        </div>
                                    </div>
                                    <blockquote class="layui-elem-quote">
                                        所选套餐信息
                                        <a class="layui-btn" onclick="selectGoods('选择套餐', '/Order/SelectGoods', 1200, 600);" style="float:right"><i class="layui-icon">&#xe61f;</i>添加套餐</a>
                                    </blockquote>
                                    <table class="layui-table layui-form">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>套餐名称</th>
                                                <th style="width:10%">购买数量</th>
                                                <th>是否活动</th>
                                                <th>箱数</th>
                                                <th>瓶数</th>
                                                <th>套餐单价</th>
                                                <th>套餐总价</th>
                                                <th>商品加价</th>
                                                <th>快递费</th>
                                                <th>预收货款</th>
                                                <th>代收货款</th>
                                                <th>实际总金额</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="myTable">
                                            <tr id="notdata">
                                                <td colspan="14" align="center" height="120"><img src="~/images/nodata.png" style="height:80px;" /><br />请添加套餐</td>
                                            </tr>

                                        </tbody>
                                    </table>
                                    <blockquote class="layui-elem-quote">订单信息</blockquote>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">订单类型</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="OrderType" value="false" title="新订单" checked>
                                            <input type="radio" name="OrderType" value="true" title="复购订单">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">发货方式</label>
                                        <div class="layui-input-block">
                                            @Html.DropDownListFor(m => m.DeliveryWay, ViewData["DeliveryWayList"] as SelectList, new { @class = "layui-input layui-select", id = "DeliveryWay", @lay_filter = "DeliveryWay" })
                                        </div>
                                    </div>
                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">订单备注</label>
                                        <div class="layui-input-block">
                                            @Html.TextAreaFor(m => m.Remark, new { @datatype = "s1-128", @autocomplete = "off", @class = "layui-textarea", @sucmsg = " ", id = "Remark", placeholder = "订单备注...(选填)" })
                                        </div>
                                    </div>


                                    <div class="layui-form-item">
                                        <label class="layui-form-label">
                                            <span class="x-red"></span>
                                        </label>
                                        <div class="layui-input-inline">
                                            <input id="btnSubmit" name="btnSubmit" type="submit" value="&#xe605; 提交订单" class="layui-btn layui-icon" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            }
        }
    </form>
    <script type="text/javascript">
        layui.use(['laydate', 'form'], function () {
            var laydate = layui.laydate;
            var form = layui.form;

        });
       
        var goodsList = [];//缓存产品ID集合
        function selectGoods(title, url, w, h) {
            layer.open({
                title: title,
                type: 2,
                content: url,
                area: [w + 'px', h + 'px'],
                fix: true,
                skin: "layui-layer-molv",
                btn: ['<i class="layui-icon">&#xe605;</i> 确定','<i class="layui-icon">&#x1006;</i> 取消'],
                success: function (layero, index) {
                    //成功获得加载页面时，预先加载，将值从父窗口传到 子窗口
                    let body = layer.getChildFrame('body', index);
                    //body.find("#testvalsss").val("999感冒灵"); 
                    layui.form.render();
                },
                yes: function (index, layero) {

                    let body = layer.getChildFrame("body", index);
                    var selectVal = 0; 
                    var radios = body.find('input[type="checkbox"][name="checkCode"]');
                    for (var i = 0; i < radios.length; i++) {
                        if (radios[i].checked) {
                            //alert(radios[i].value);
                            selectVal = radios[i].value;
                            break; // 找到后退出循环
                        }
                    }
                    if (selectVal > 0) {
                        //判断是否存在该商品
                        if (goodsList.includes(selectVal)) {
                            layer.confirm('温馨提示，该商品已在套餐信息中存在，不可重复勾选！', { icon: 2, title: '提示', anim: 6, }, function (indexs) {
                                layer.close(indexs);
                            });
                            return false;
                        }
                        var msg = "选择该商品，您确定吗？";
                        layer.confirm(msg, { icon: 3, title: '提示' }, function (indexs) {

                            goodsList.push(selectVal);//添加到集合
                            //获取商品详情信息列表
                            LoadSelectGoodsInfo(selectVal)
                            layer.close(indexs);
                            layer.close(index);
                        });
                        return false;
                    } else
                    {
                        layer.confirm('对不起，请选中您要操作的记录！', { icon: 2, title: '提示', anim: 6, }, function (indexs) {
                            layer.close(indexs);
                        });
                        return false;
                    }
                    layer.close(index);
                }
            });
        }
        ///获取商品详细信息并展示到页面
        function LoadSelectGoodsInfo(selectGoodsId) {
            $.ajax({
                type: "POST",
                url: "/Goods/GetGoodsDetail",
                data: { GoodsId: selectGoodsId },
                success: function (obj) {
                    if (obj.code == 200) {
                        insertRowBeforeLast(obj.data);
                    }
                }
            })

        }
   
        //在Table最后一行前插入一条数据数据
        function insertRowBeforeLast(data) {
            //console.log(data);
            var rowdata = `{Id:${data.Id},Lable:${data.Lable},CalcSpec: ${data.CalcSpec}, Stock: '${data.Stock}',SpecNum:${data.SpecNum},CounterPrices:${data.CounterPrices},ActivityPrices:${data.ActivityPrices}}`;
            var table = document.getElementById("myTable");//获取表格元素
            var rowCount = table.rows.length;//单元格行数
            if (rowCount == 1) {
               rowCount= rowCount - 1;
            } else {

                rowCount=rowCount - 2;
            }
            var newRow = table.insertRow(rowCount);//倒数第二行
            newRow.insertCell(0).innerHTML = (`<span id="index_${goodsList.length}">${goodsList.length}</span>`);
            newRow.insertCell(1).innerHTML = data.Name;
            newRow.insertCell(2).innerHTML = (`<div class="layui-input-inline">
                                                  <input type="button" value="-" class="layui-btn btn-number layui-btn-sm" onclick="changeNumber(-1,${rowdata})" />
                                                  <input type="number" class="layui-input txt-number" id="txtnumber_${data.Id}" name="txtnumber" value="0"  min="0" max="${data.Stock}" readonly="readonly" >
                                                  <input type="button" value="+" class="layui-btn btn-number layui-btn-sm" onclick="changeNumber(1,${rowdata})" />
                                                  </div>`);
            newRow.insertCell(3).innerHTML = (`<button type="button" class="layui-btn layui-btn-radius ${data.Lable == true ? 'layui-bg-orange' : 'layui-bg-blue'}">${data.Lable == true ? '常规套餐' : '活动套餐'}</button>`);
            newRow.insertCell(4).innerHTML = (`<span id="calcSpec_${data.Id}">${data.CalcSpec}</span>`);
            newRow.insertCell(5).innerHTML = (`<span id="specNum_${data.Id}">${data.SpecNum}</span>`);
            newRow.insertCell(6).innerHTML = (`<span id="prices_${data.Id}">${data.Lable == false ? data.CounterPrices.toFixed(2) : data.ActivityPrices.toFixed(2)}</span> ￥`);
            newRow.insertCell(7).innerHTML = (`<span id="totalPrices_${data.Id}">${data.Lable == false ? data.CounterPrices.toFixed(2) : data.ActivityPrices.toFixed(2) }</span> ￥`);
            newRow.insertCell(8).innerHTML = (`<input type="text" id="addPrices_${data.Id}" placeholder="输入加价金额" autocomplete="off" class="layui-input"  value="0.00">`);
            newRow.insertCell(9).innerHTML = (`<input type="text" id="addFreight_${data.Id}" placeholder="输入加价运费金额"  autocomplete="off" class="layui-input" value="0.00">`);
            newRow.insertCell(10).innerHTML = (`<input type="text" id="advancePay_${data.Id}" placeholder="输入预付款金额"  autocomplete="off" class="layui-input"  value="0.00">`);
            newRow.insertCell(11).innerHTML = (`<span id="finalPayment_${data.Id}">0.00</span> ￥`);
            newRow.insertCell(12).innerHTML = (`<span id="totalPayment_${data.Id}">0.00</span> ￥`);
            newRow.insertCell(13).innerHTML = (`<a title="点击移除该商品" class="layui-btn layui-btn-xs layui-btn-danger" onclick="onDelProdouct(${goodsList.length},${rowdata})" href="javascript:;"><i class="layui-icon">&#xe640;</i>删除</a>`);
            if (rowCount ==0) {
                appendRowBeforeLast();
            }

            changeNumber(1, data)//添加产品数量
            onAddPrice(data); //套餐加价金额
            onAddFreight(data); //运费加价金额
            onAdvancePay(data); //预付款金额
            addTotalPrices(data.Id); //计算实际付款总金额
        }
        //追加Table最后一行:合计
        function appendRowBeforeLast()
        {
            var table = document.getElementById("myTable");//获取表格元素
            var rowCount = table.rows.length;//单元格行数

            var newRow = table.insertRow(rowCount - 1);//倒数第二行
            newRow.insertCell(0).innerHTML = "合计";
            newRow.insertCell(1).innerHTML = "";
            newRow.insertCell(2).innerHTML = (`<span id="allNumber">0</span>`);
            newRow.insertCell(3).innerHTML = (``);
            newRow.insertCell(4).innerHTML = (`<span id="allCalcSpec">0</span>`);
            newRow.insertCell(5).innerHTML = (`<span id="allSpecNum">0</span>`);
            newRow.insertCell(6).innerHTML = (`<span id="allPrices"></span>`);
            newRow.insertCell(7).innerHTML = (`<span id="allTotalPrices">0.00</span> ￥`);
            newRow.insertCell(8).innerHTML = (`<span id="alladdPrices">0.00</span> ￥`);
            newRow.insertCell(9).innerHTML = (`<span id="alladdFreight">0.00</span> ￥`);
            newRow.insertCell(10).innerHTML = (`<span id="alladvancePay">0.00</span> ￥`);
            newRow.insertCell(11).innerHTML = (`<span id="allFinalPayment">0.00</span> ￥`);
            newRow.insertCell(12).innerHTML = (`<span id="allTotalPayment">0.00</span> ￥`);
            newRow.insertCell(13).innerHTML = "";
            newRow.style.color = "red";//添加字体颜色样式

            $("#notdata").hide();  //当选择商品，则隐藏暂无数据的显示
        }

        //添加商品数量
        function changeNumber(direction, data) {
            var qtyInput = document.getElementById('txtnumber_' + data.Id);
            var currentQty = parseInt(qtyInput.value, 10);
            var newQty = currentQty + direction;
       
            if (newQty < 1) {
                newQty = 1;
            }
            if (newQty >= data.Stock)
            {
                newQty = data.Stock;
            }

            // 这里可以添加更多的校验逻辑，比如检查库存等
            //商品结算显示
            qtyInput.value = newQty;
            $('#calcSpec_' + data.Id).text(newQty * data.CalcSpec);
            $('#specNum_' + data.Id).text(newQty * data.SpecNum);
            //套餐单价
            var price = (data.Lable == false ? data.CounterPrices : data.ActivityPrices);
            $('#totalPrices_' + data.Id).text((newQty * price).toFixed(2));//总价=购买数量*套餐单价

            //合计结算
            AddMyTotalPrices(data)
        }
        //合计结算
        function AddMyTotalPrices(data)
        {
            //合计
            var allNumber = 0;//合计商品总数
            var allCalcSpec = 0;//合计商品箱数
            var allSpecNum = 0;//合计商品瓶数
            var allTotalPrices = 0;//合计商品总价
            var alladdPrices = 0;//合计套餐加价金额
            var alladdFreight = 0;//合计运费加价金额
            var alladvancePay = 0;//合计预付款金额

            var orderGoods = "";//订单商品缓存
            goodsList.forEach(function (itemId) {
                allNumber += Number($('#txtnumber_' + itemId).val());
                allCalcSpec += (Number($('#calcSpec_' + itemId).text()));
                allSpecNum += (Number($('#specNum_' + itemId).text()));
                allTotalPrices += Number($('#totalPrices_' + itemId).text());
                alladdPrices += Number($('#addPrices_' + itemId).val());
                alladdFreight += Number($('#addFreight_' + itemId).val());

                var totalPrices = (parseFloat($('#totalPrices_' + data.Id).text()) + getValue($('#addPrices_' + data.Id).val()) + getValue($('#addFreight_' + data.Id).val()));
                if (Number($('#advancePay_' + itemId).val()) > totalPrices) {
                    alladvancePay += totalPrices;
                    $('#advancePay_' + data.Id).val(totalPrices);
                    $('#alladvancePay').text(totalPrices);
                } else {
                    alladvancePay += Number($('#advancePay_' + itemId).val());
                }

                //拼接订单商品
                orderGoods += itemId + '_' + $('#txtnumber_' + itemId).val() + '_' + $('#addPrices_' + itemId).val() + '_' + $('#addFreight_' + itemId).val() + '_' + $('#advancePay_' + itemId).val() + ',';//商品Id_购买数量_商品加价金额_运费金额_预付款金额,10001_3_100_5_1000
            });
            $('#allNumber').text(allNumber);
            $('#allCalcSpec').text(allCalcSpec);
            $('#allSpecNum').text(allSpecNum);
            $('#allTotalPrices').text(allTotalPrices.toFixed(2));//总价=购买数量*套餐单价
            $('#alladdPrices').text(alladdPrices.toFixed(2));
            $('#alladdFreight').text(alladdFreight.toFixed(2));
            $('#alladvancePay').text(alladvancePay.toFixed(2));
            $('#OrderGoods').val(orderGoods);
            addTotalPrices(data.Id); //计算实际付款总金额
        }
        //套餐加价金额
        function onAddPrice(data)
        {
            // 监听指定开始的事件
            $("#addPrices_" + data.Id).bind('input propertychange', function () {
                if (Number($("#addPrices_" + data.Id).val()) < 0) {
                    var msg = '输入有误，套餐加价金额只不能小于0';
                    layer.msg(msg, { icon: 5, title: '提示' }, function (index) {
                        layer.close();
                    });
                    $('#addPrices_' + data.Id).val('0.00');
                    $('#alladdPrices').text('0.00');
                } 

                //合计结算
                AddMyTotalPrices(data)
            })
        }
        //运费加价金额
        function onAddFreight(data) {
            // 监听指定开始的事件
            $("#addFreight_" + data.Id).bind('input propertychange', function () {
                if (Number($("#addFreight_" + data.Id).val()) < 0) {
                    var msg = '输入有误，运费加价金额金额只不能小于0';
                    layer.msg(msg, { icon: 5, title: '提示' }, function (index) {
                        layer.close();
                    });
                    $('#addFreight_' + data.Id).val('0.00');
                    $('#alladdFreight').text('0.00');
                } 
                //合计结算
                AddMyTotalPrices(data)
            })
        }
        //预付款金额
        function onAdvancePay(data) {
            // 监听指定开始的事件
            $("#advancePay_" + data.Id).bind('input propertychange', function () {
                if (Number($("#advancePay_" + data.Id).val()) < 0 || Number($("#advancePay_" + data.Id).val()) > Number($('#totalPrices_' + data.Id).text())) {

                    var totalPrices = (parseFloat($('#totalPrices_' + data.Id).text()) + getValue($('#addPrices_' + data.Id).val()) + getValue($('#addFreight_' + data.Id).val())).toFixed(2);
                    if (totalPrices > 0) {
                        if (Number($("#advancePay_" + data.Id).val()) > totalPrices) {
                            var msg = '输入有误，预付款金额不能超过订单总金额！';
                            layer.msg(msg, { icon: 5, title: '提示' }, function (index) {
                                $('#advancePay_' + data.Id).val(totalPrices);
                                $('#alladvancePay').text(totalPrices);

                                layer.close();
                            });
                        }
                        //合计结算
                        AddMyTotalPrices(data)
                    } else {
                        if (Number($('#totalPrices_' + data.Id).text()) > 0) {
                            var msg = '输入有误，预付款金额只限于（0~' + $('#totalPrices_' + data.Id).text() + '）区间！';
                            layer.msg(msg, { icon: 5, title: '提示' }, function (index) {
                                layer.close();
                            });
                        } else {
                            $('#advancePay_' + data.Id).val('0.00');
                            $('#alladvancePay').text('0.00');
                        }
                    }
                }
            })
        }
        //实际付款总金额
        function addTotalPrices(Id)
        {
            //产品实际总金额=套餐总价+套餐加价金额=运费金额
            var totalPrices = (parseFloat($('#totalPrices_' + Id).text()) + getValue($('#addPrices_' + Id).val()) + getValue($('#addFreight_' + Id).val())).toFixed(2);
            //产品待收尾款金额=实际总金额-预付款金额
            var finalPayment = (totalPrices - getValue($('#advancePay_' + Id).val())).toFixed(2);

            //合计实际总金额=套餐总价+套餐加价金额=运费金额
            var allTotalPayment = (parseFloat($('#allTotalPrices').text()) + parseFloat($('#alladdPrices').text()) + parseFloat($('#alladdFreight').text())).toFixed(2);
            //合计待收尾款金额=实际总金额-预付款金额
            var allFinalPayment = (allTotalPayment - parseFloat($('#alladvancePay').text())).toFixed(2);

            $('#finalPayment_'+Id).text(finalPayment);
            $('#totalPayment_'+Id).text(totalPrices);
            $('#allFinalPayment').text(allFinalPayment);
            $('#allTotalPayment').text(allTotalPayment);
        }
        //移除商品
        function onDelProdouct(rowLength, data)
        {
            var msg = "移除该商品，您确定吗？";
            layer.confirm(msg, { icon: 3, title: '提示' }, function (indexs) {
                var table = document.getElementById("myTable");  // 获取要删除的行对象
                // 删除最后一行
                table.deleteRow(rowLength - 1);// 删除指定行
                goodsList = goodsList.filter(item => item != data.Id); // 商品Id移除数组元素
                if (goodsList.length == 0) {
                    $("#notdata").show();  //暂无数据的显示
                    table.deleteRow(goodsList);// 最后一行指定行
                }
                //合计结算
                AddMyTotalPrices(data)
                layer.close(indexs);
            });
            return false;
        }
        function getValue(inputVal) {
            var value = 0;
            if (inputVal != '')
            {
                try {
                   value= parseFloat(inputVal);
                } catch (e) {

                }
               
                if (value < 0)
                {
                    value = 0;
                }
            }
            return value;
        };
       
    </script>
</body>
</html>
